﻿using Prism.Ioc;
using Prism.Modularity;
using Prism.Regions;
using Prism.Unity;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Unity;
using Xcj.Mes.Core.FileHelper;
using Xcj.Mes.WholeLine.DataBase.Entity;
using Xcj.Mes.WholeLine.Plc.Inovance;
using Xcj.Mes.WholeLine.Plc.Interface;
using Xcj.Mes.WholeLine.Plc.Keyence;
using Xcj.Mes.WholeLine.Plc.Omron;
using Xcj.Mes.WholeLine.Plc.Panasonic;
using Xcj.Mes.WholeLine.ZH.HG.Shell.ViewModels;
using Xcj.Mes.WholeLine.ZH.HG.Shell.ViewModels.Config;
using Xcj.Mes.WholeLine.ZH.HG.Shell.ViewModels.Production;
using Xcj.Mes.WholeLine.ZH.HG.Shell.Views;
using Xcj.Mes.WholeLine.ZH.HG.Shell.Views.WorkRegion.Config;
using Xcj.Mes.WholeLine.ZH.HG.Shell.Views.WorkRegion.Production;

namespace Xcj.Mes.WholeLine.ZH.HG.Shell
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : PrismApplication
    {
        //public static IPlc[] Plcs = null;
        public static AccountEntity accountEntity = new AccountEntity();
        public static DeviceConfigEntity deviceConfigEntity = new DeviceConfigEntity();

        public App()
        {
            _ = MyFileHelper.myFileHelper;

            if (!Directory.Exists(".\\Modules "))
                try { Directory.CreateDirectory(".\\Modules"); } catch { }

            //Task.Run(() =>
            //{
            //    //Plcs = new IPlc[4]
            //    //{
            //    //    new PanasonicPlc("钉卷"),
            //    //    new OmronPlc("组立"),
            //    //    new PanasonicPlc("老化"),
            //    //    new InovancePlc("座板"),
            //    //};
            //    Plcs = new IPlc[1]
            //    { 
            //        new PanasonicPlc("钉卷")
            //    };
            //    //修改配置和数据地址后，调用Plcs[***].Init();
            //    //plc数据引用Plcs[0].DictPlcAddress["***"]
            //});

            this.Exit += ((o,e) =>
            {
                MyFileHelper.myFileHelper.Dispose();
            });
        }

        protected override Window CreateShell()
        {
            // 创建主窗口
            return Container.Resolve<ShellWindow>();
        }

        protected override void InitializeShell(Window shell)
        {
            base.InitializeShell(shell);
            Application.Current.MainWindow.Show();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // 在这里注册全局单例服务或类型
            // 例如：containerRegistry.RegisterSingleton<ISomeGlobalService, SomeGlobalService>();
            // 注册全局服务
            //containerRegistry.RegisterSingleton<ILogger, DebugLogger>();
            //containerRegistry.RegisterSingleton<IEventAggregator, EventAggregator>();
            
            containerRegistry.RegisterForNavigation<MainView, MainViewModel>(nameof(MainView));

            
            containerRegistry.RegisterForNavigation<DeviceView, DeviceViewModel>(nameof(DeviceView));

            containerRegistry.RegisterForNavigation<ProductionView, ProductionViewModel>(nameof(ProductionView));
        }

        protected override IModuleCatalog CreateModuleCatalog()
        {
            // 选择动态加载模块的方式之一：
            // 方式1: 从指定目录加载所有模块 (推荐用于真正的动态插件化)
            // 确保模块 DLL 及其依赖项都复制到 ./Modules 目录下
            return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };

            // 方式2: 从配置文件 (App.config) 加载模块定义
            // return new ConfigurationModuleCatalog();

            // 方式3: 直接在代码中注册模块 (较静态，但简单)
            // var catalog = new ModuleCatalog();
            // catalog.AddModule<ModuleAModule>();
            // catalog.AddModule<ModuleBModule>();
            // return catalog;
        }

        protected override sealed IContainerExtension CreateContainerExtension()
        {
            return new UnityContainerExtension();
        }

        protected override void OnInitialized()
        {
            base.OnInitialized();

            // 显示初始化界面
            //var splashScreen = Container.Resolve<SplashScreen>();
            //splashScreen.Show();

            // 初始化完成后导航到登录页
            var regionManager = Container.Resolve<IRegionManager>();
            regionManager.RequestNavigate("ShellRegion", typeof(MainView).Name);
        }

        private void MenuExit(object sender, RoutedEventArgs e)
        {
            try { Application.Current?.MainWindow?.Close(); } catch { }
        }

        private void MenuShow(object sender, RoutedEventArgs e)
        {
            if ((System.Windows.Application.Current?.MainWindow == null) || (System.Windows.Application.Current?.Dispatcher == null))
                return;

            ThreadPool.QueueUserWorkItem(delegate
            {
                SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(App.Current?.Dispatcher));
                SynchronizationContext.Current?.Post(p =>
                {
                    try
                    {
                        if (App.Current.MainWindow.Visibility == Visibility.Visible)
                        {
                            App.Current.MainWindow.Hide();
                            App.Current.MainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            App.Current.MainWindow.WindowState = WindowState.Maximized;
                        }
                        else
                        {
                            App.Current.MainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            App.Current.MainWindow.WindowState = WindowState.Maximized;
                            App.Current.MainWindow.Topmost = false;
                            App.Current.MainWindow.Show();
                        }
                    }
                    catch { }
                }, null);
            });
        }
    }
}
